package com.fit.dao.course;

import java.util.Date;
import java.util.List;

import org.apache.tapestry5.annotations.Log;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.fit.entities.course.Course;
import com.fit.entities.professor.Professor;
import com.fit.entities.user.User;
import com.fit.services.Authenticator;

public class CourseDAOImpl implements CourseDAO {

	@Inject
	private Session session;
	@Inject
	private Authenticator authenticator;

	public User getUser() {
		if (authenticator.isLoggedIn()) {
			return authenticator.getLoggedUser();
		}
		return null;
	}

	@Log
	public boolean save(Course newCourse) {
		if (newCourse != null) {
			session.save(newCourse);
			return true;
		}
		return false;
	}

	@Log
	public boolean delete(Course course) {
		if (course != null) {
			session.delete(course);
			return true;
		}
		return false;
	}

	@Log
	public boolean update(Course course) {
		if (course != null) {
			session.update(course);
			return true;
		}
		return false;
	}

	@Log
	public List findAll() {
		return session.createCriteria(Course.class).list();
	}

	@Log
	public boolean deleteByID(Long id) {
		Course u = findByID(id);
		if (u != null) {
			delete(u);
			return true;
		}
		return false;
	}

	@Log
	public Course findByID(Long id) {
		if (id != null) {
			return (Course) session.get(Course.class, id);
		}
		return null;
	}

	@Log
	public Course findByIdCourseAndBeginingDate(int courseId, Date beginingDate) {
		if (courseId == 0 || beginingDate == null) {
			return null;
		}

		if (courseId==(0) || beginingDate.equals("")) {
			return null;
		}

		List l = session.createCriteria(Course.class)
				.add(Restrictions.eq("userName", courseId))
				.add(Restrictions.eq("password", beginingDate)).list();
		Course u = null;
		if (l != null) {
			if (l.size() > 0) {
				u = (Course) l.get(0);
			}
		}
		return u;
	}
	public List findByUser() {
		return session.createCriteria(Professor.class).add(Restrictions.eq("professorId", getUser())).list();
	}
}
